// 导入基础库
import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
// 导入配置参数
// 导入处理函数
import com from '../../../utils/common';
import { getJSON } from '../../../utils/request';
// 导入UI组件
import { Upload, Space, Image, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
const { Dragger } = Upload;
const { confirm } = Modal;
// 导入LESS样式
import styles from './upload_img.less';

const PageView = (props) => {
  // 初始化参数------------------------------------------------
  const { dispatch: dp, ids} = props;

  const [fileList, setFileList] = useState([]);
  const [init, setinit] = useState(true);

  const update = async () => {
      var x = await getJSON(process.env.postUrl + '/api/imgs/' + ids);
      setFileList(x);
  };

  // update()

  const beforeUpload = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const img = document.createElement('img');
        img.src = reader.result;
        img.onload = () => {
          const {
            naturalWidth: originWidth,
            naturalHeight: originHeight,
          } = img;
          const maxWidth = 800,
            maxHeihgt = 800;

          let targetWidth = originWidth,
            targetHeight = originHeight;
          // 等比例计算超过最大限制时缩放后的图片尺寸
          if (originWidth > maxWidth || originHeight > maxHeihgt) {
            if (originWidth / originHeight > 1) {
              // 宽图片
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth),
              );
            } else {
              // 高图片
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight),
              );
            }
          }
          const canvas = document.createElement('canvas');
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          const ctx = canvas.getContext('2d');
          ctx.clearRect(0, 0, targetWidth, targetHeight);
          ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
          canvas.toBlob(resolve);
        };
      };
    });
  };

  // 渲染UI组件------------------------------------------------
  return (
    <div>
      <Dragger
        name={ids}
        action={`${process.env.postUrl}/api/upload`}
        maxCount={1}
        showUploadList={false}
        beforeUpload={beforeUpload}
        onChange={async ({ file }) => {
          let status = file.response;
          if (status) {
            if (status.status === 200) {
              com.msg(status.msg.type, status.msg.msg);
              update();
            }
          }
        }}
      >
        <p className="ant-upload-drag-icon">
          <PlusOutlined />
        </p>
        <p className="ant-upload-text">点击或拖入上传图片档案</p>
      </Dragger>
      <div style={{ marginTop: 20 }}>
        <Image.PreviewGroup>
          <Space size={[10, 10]} wrap>
            {fileList.map((file, id) => (
              <div key={id} style={{ position: 'relative' }}>
                <div
                  className={styles.delet}
                  onClick={() => {
                    confirm({
                      title: '询问?',
                      content: '是否要删除该图片档案',
                      onOk() {
                        dp({
                          type: 'socketio/emit',
                          payload: { type: 'remove_img', data: file },
                        });
                        update();
                      },
                    });
                  }}
                >
                  X
                </div>
                <Image
                  width={200}
                  src={`${process.env.postUrl}/imgs/${file.filename}`}
                />
              </div>
            ))}
          </Space>
        </Image.PreviewGroup>
      </div>
    </div>
  );
};

export default connect(({ table, socketio }) => ({
  table,
  socketio,
}))(PageView);
